global class BatchPopulateLowestOppIdOnAcc implements Database.Batchable<sObject> {
	global string query;
	global BatchPopulateLowestOppIdOnAcc() {
		query = 'Select a.id,a.OppyIdWithLowestStatusValue__c' + 
     			' from Account a' + 
     			' where a.RecordType.Name = \'West - Student Account\'' + 
     			' and OppyIdWithLowestStatusValue__c = null';
	}
	global Database.Querylocator start(Database.BatchableContext BC) {
		return Database.getQueryLocator(query);
	}
	
	global void execute(Database.BatchableContext BC,List<Account> updAcc) {
		Set<Id> accId = new Set<Id>();
     	for(Account a1: updAcc) {
     		accId.add(a1.Id);
     	}
     	system.debug('updateAccountFieldLSV');
    	List<Opportunity> oppIdToBeUpdated = [Select o.AccountId,Id,o.Status_Fraud_Value__c,o.Lead_Creation_Date__c,o.Account.id                                             
                                              From Opportunity o
                                              where o.RecordType.Name = 'West - Student Application' and o.Account.Id =:accId];
    	system.debug(oppIdToBeUpdated.size());
    	Map<ID,Opportunity> mapFraudOpp = new Map<ID,Opportunity>();
    	integer i =0;
    	for (Opportunity o : oppIdToBeUpdated) {
    		i++;
    		system.debug(o.id);
			if(mapFraudOpp.size()>0){
				if(mapFraudOpp.ContainsKey(o.accountId)) {
					if(mapFraudOpp.get(o.accountId).status_Fraud_Value__c > o.Status_Fraud_Value__c ) {
						mapFraudOpp.put(o.accountId,o);
					} 
					else if (mapFraudOpp.get(o.accountId).status_Fraud_Value__c == o.Status_Fraud_Value__c ) {
						if(mapFraudOpp.get(o.accountId).Lead_Creation_Date__c < o.Lead_Creation_Date__c) {
							mapFraudOpp.put(o.accountId,o);
						}
					}
				}
				else
					mapFraudOpp.put(o.accountId,o);
			}
			else
				mapFraudOpp.put(o.accountId,o);			
		}
		
		system.debug('iiiii');
		system.debug(i);
		if(mapFraudOpp.size() >0) {
			List<Account> acc = new List<Account>();
			for(Opportunity o1: mapFraudOpp.values()) {
				Account a = o1.Account;			
				a.OppyIdWithLowestStatusValue__c = o1.Id;
				acc.add(a);
			}
			update acc;
		}
	}
	
	global void finish(Database.BatchableContext BC) {
		
	}
}